package com.android.sunflower.ui

import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Message
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationBuilderWithBuilderAccessor
import androidx.core.app.NotificationCompat
import androidx.navigation.NavController
import androidx.navigation.findNavController
import androidx.navigation.fragment.NavHostFragment
import androidx.room.Room
import com.android.sunflower.R
import com.android.sunflower.databinding.ActivityMainBinding
import com.android.sunflower.logic.NotifyWaterService
import com.android.sunflower.logic.Repository
import com.android.sunflower.logic.room.AppDataBase
import com.android.sunflower.logic.room.entities.Flower
import com.android.sunflower.utils.PicToBitmap
import kotlin.concurrent.thread

class MainActivity : AppCompatActivity() {

    inner class MyHandler:Handler(){
        @RequiresApi(Build.VERSION_CODES.O)
        override fun handleMessage(msg: Message) {
            if(msg.what==NOTIFY_WATER){
                //构造notificationBuilder
                val intent=Intent(this@MainActivity,MainActivity::class.java)
                val pendingIntent=PendingIntent.getActivity(this@MainActivity,1,intent,PendingIntent.FLAG_IMMUTABLE)
                val builder= Notification.Builder(this@MainActivity,WATER_CHANNEL_ID).apply {
                    setSmallIcon(R.mipmap.ic_launcher)
                    setContentTitle("注意浇水")
                    setContentText("你的花园中有植物快要枯萎啦！")
                    setContentIntent(pendingIntent)
                }
                //构造notification并设置flag
                val notification=builder.build()
                notification.flags=Notification.FLAG_AUTO_CANCEL
                //构造channel
                val notificationChannel=NotificationChannel(WATER_CHANNEL_ID, WATER_CHANNEL_ID,NotificationManager.IMPORTANCE_HIGH)
                //构造notificationManager
                val notificationManager=applicationContext.getSystemService(NOTIFICATION_SERVICE) as NotificationManager
                //创建channel
                notificationManager.createNotificationChannel(notificationChannel)
                //发送通知
                notificationManager.notify(1,notification)
            }

        }
    }
    companion object{
        const val WATER_CHANNEL_ID="浇水提醒"
        const val NOTIFY_WATER=110
        var runningInstance:MainActivity?=null
        @SuppressLint("StaticFieldLeak")
        var navController:NavController?=null

        val handler get()=_handler
        private var _handler:MyHandler?=null
    }
    private lateinit var mainBinding:ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mainBinding=ActivityMainBinding.inflate(layoutInflater)
        setContentView(mainBinding.root)

        runningInstance=this

        _handler=MyHandler()


        //使用FragmentContainerView创建的NavHostFragment必须使用findFragmentById才可以正确获取NavController对象。
        val navHostFragment=supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
        navController=navHostFragment.navController

        //判断是否第一次运行
        val preference=getPreferences(Context.MODE_PRIVATE)
        val firstRun=preference.getBoolean("first_run",true)
        thread {
            if(firstRun){
                val sunFlower=Flower("向日葵",
                    "向日葵原产于美洲，中国地区也有栽培。是一种菊科向日葵属的植物，茎直立，粗壮，圆形多棱角，为白色粗硬毛，夏季开花。向日葵的花语是“太阳、沉默的爱、爱慕；”野生向日葵的花语是“投缘”。",
                    "①水分：不同生育阶段对水分要求差异很大\n" +
                            "②温度：发芽的最适温度为31～37℃\n" +
                            "③光照：生育期间光照要充足",
                    3,
                    R.drawable.sunflower_pic)

                val lily=Flower("百合花",
                    "百合原产于中国，是一种百合科百合属的植物。因其鳞茎由许多白色鳞片层环抱而成，状如莲花，因而取 “百年好合”之意命名。百合的花语是“百年好合、美好家庭、伟大的爱”。",
                    "①土壤：疏松、肥沃的土壤\n" +
                            "②光照：要充足，可略微遮阴\n" +
                            "③水分：保持土壤湿润，适当喷水\n" +
                            "④施肥：每半月施肥一次，花期需追肥\n" +
                            "⑤温度：平时12-18℃，花期26-24℃",
                    1,
                    R.drawable.lily_pic)
                val hoaryStock=Flower("紫罗兰",
                    "紫罗兰原产于地中海沿岸，在中国南部地区广泛栽培，是一种十字花科紫罗兰属的植物。它是欧洲名花之一，花朵茂盛，花色鲜艳，香气浓郁，花期长，花序也长，为众多爱花者所喜爱，适宜于盆栽观赏和布置花坛、台阶、花径等，它的整株花朵可作为花束。紫罗兰的花语是“永恒的美与爱、质朴、美德、盛夏的清凉”。",
                    "①土壤：排水性好且中性偏碱性的土壤\n" +
                            "②光照：需要一定光照，但要避免直射光\n" +
                            "③温度：15-18℃\n" +
                            "④浇水：温度高时多浇，温度低时少浇",
                    10,
                    R.drawable.hoary_stock_pic
                )
                Repository.insertFlowers(sunFlower,lily,hoaryStock)
                preference.edit().putBoolean("first_run",false).apply()
            }
        }

        //启动服务
        val intent= Intent(this, NotifyWaterService::class.java)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(intent)
        }else{
            startService(intent)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        runningInstance=null

        navController=null

        _handler=null
    }
}